package com.yc.zk.config;

import com.yc.zk.common.CommonHelper;
import com.yc.zk.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.List;

@Slf4j
public class ZkWatcher implements Watcher {

    @Override
    public void process(WatchedEvent watchedEvent) {
        try {
            if (Event.KeeperState.SyncConnected == watchedEvent.getState()) {
                System.out.println("已经触发了" + watchedEvent.getType() + "事件！");
                switch (watchedEvent.getType()) {
                    case NodeChildrenChanged:
                        //重新选举
                        List<String> stringList = Constants.zooKeeper.getChildren(Constants.zookeeperRegistName, false);
                        String masterHost = CommonHelper.findMaster(stringList);
                        if (Constants.nodeSequence.equals(masterHost)) {
                            //变更leader，重新分配所有任务
                            Constants.isLeader = true;
                            log.info("zk节点变化，您是leader节点！");
                        } else {
                            Constants.isLeader = false;
                            log.info("zk节点变化，您是follower节点！");
                        }
                        break;
                    case None:
                        break;
                    case NodeCreated:
                        break;
                    case NodeDeleted:
                        break;
                    case NodeDataChanged:
                        break;
                    default:
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }
}
